package com.example.base.base.viewmodel

import android.text.TextUtils
import com.example.base.base.bean.BaseBean
import com.example.base.bean.ResponseResult
import com.google.gson.JsonParseException
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * @Description
 * @department 城市元宇宙组
 * @Author niushilong
 * @Date 2024-04-05 13:49
 */
open class BaseRepository {

    // 直接调用，没有错误处理
    suspend inline fun<T> handleApiCall(call: suspend () -> BaseBean<T>): BaseBean<T> {
        return call.invoke()
    }

    suspend fun<T> handleErrorApiCall(call: suspend () -> ResponseResult<T>, errorMessage: String = ""): ResponseResult<T> {
        return try {
            call()
        }catch (e: Exception){
            if (!TextUtils.isEmpty(errorMessage)){
                ResponseResult.Error(IOException(errorMessage))
            }else{
                ResponseResult.Error(handleExceptionMessage(e))
            }
        }
    }

    //处理自定义错误消息
    fun handleExceptionMessage(e: Exception): IOException {
        return when (e) {
            is UnknownHostException -> IOException("Unable to access domain name, unknown domain name.")
            is JsonParseException -> IOException("Data parsing exception.")
            is HttpException -> IOException("The server is on business. Please try again later.")
            is ConnectException -> IOException("Network connection exception, please check the network.")
            is SocketException -> IOException("Network connection exception, please check the network.")
            is SocketTimeoutException -> IOException("Network connection timeout.")
            is RuntimeException -> IOException("Error running, please try again.")
            else -> IOException("unknown error.")
        }

    }

}